package vn.com.vega.music.view.custom;

import vn.com.vega.chacha.R;
import vn.com.vega.music.utils.Util;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class LoadingView extends RelativeLayout {
	private ProgressBar mLoadingbar;
	private TextView mLoadingText;
	private Button mRetryBtn;
	private RetryListener listener;
	private Context mContext;

	public LoadingView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		init(context);
	}

	public LoadingView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		init(context);
	}

	public LoadingView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		init(context);
	}

	public void setRetryListener(RetryListener listener) {
		this.listener = listener;
	}

	private void init(Context ctx) {
		mContext = ctx;
		LayoutInflater inflater = (LayoutInflater) ctx
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.layout_loading_data, this);
		mLoadingbar = (ProgressBar) findViewById(R.id.feature_list_progress);
		mLoadingText = (TextView) findViewById(R.id.feature_help_label);
		mRetryBtn = (Button) findViewById(R.id.feature_help_btn);
		mRetryBtn.setOnClickListener(onRetry);
	}

	private View.OnClickListener onRetry = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mLoadingbar.setVisibility(View.VISIBLE);
			mRetryBtn.setVisibility(View.GONE);
			mLoadingText.setText(mContext.getString(R.string.loading_data));
			if (listener != null) {
				listener.onRetry();
			}
		}
	};

	public void startLoading() {
		this.setVisibility(View.VISIBLE);
		mLoadingbar.setVisibility(View.VISIBLE);
		mRetryBtn.setVisibility(View.GONE);
		mLoadingText.setVisibility(View.VISIBLE);
		mLoadingText.setText(mContext.getString(R.string.loading_data));
	}

	public void loadingFinish(boolean isSuccess, String failMessage) {
		if (isSuccess) {
			this.setVisibility(View.GONE);
		} else {
			this.setVisibility(View.VISIBLE);
			mRetryBtn.setVisibility(View.VISIBLE);
			mLoadingbar.setVisibility(View.GONE);
			mLoadingText.setVisibility(View.VISIBLE);
			if (Util.checkStringIsemptyOrNull(failMessage)) {
				mLoadingText
						.setText(mContext.getText(R.string.load_data_error));
			} else {
				mLoadingText.setText(failMessage);
			}
		}
	}

	public interface RetryListener {
		public void onRetry();
	}
}
